Unit 03: Standard and Weighted K-Nearest Neighbors
1. Introduction
The KNN
algorithm is the first supervised classification model we will study in depth.
Its power comes from beautiful simplicity: to classify a new point, look at the
k closest labeled training points and take a majority vote. This unit covers the
algorithm's place in the taxonomy of ML methods, distance metrics, the critical
choice of k, the equal-vote problem, and how weighted KNN fixes it.
Learning Objectives
Distinguish parametric vs. non-parametric and eager vs. lazy learning paradigms
Explain the 5-step standard KNN algorithm and trace it on toy data
Compute Euclidean, Manhattan, and Minkowski distances between data points
Choose a reasonable k value and justify the bias-variance tradeoff of k
Describe why feature scaling is mandatory before KNN
Apply distance-weighted KNN to fix the equal-vote problem and explain the weighting variants
2. Theory
2.1 ML Algorithm Taxonomy
Parametric vs. Non-Parametric
Lazy vs. Eager
Dimension
Parametric
Non-Parametric
Parameter count
Fixed, independent of data size
Grows with data size
Assumptions
Strong (linearity, normality, …)
Few / none
Examples
LinReg, LogReg, Naïve Bayes
KNN, Decision Trees, Ensembles
Pros
Fast, require less data
Flexible, capture complex patterns
Cons
Too restrictive if assumptions fail
Need more data, computationally costly
Dimension
Lazy Learning
Eager Learning
Training phase
Stores the data only (zero compute)
Builds explicit model immediately
Work happens when?
Prediction time
Training time
Speed: train
Fast
Slow
Speed: predict
Slow (O(n) per prediction)
Fast
Example
KNN, case-based reasoning
Neural Nets, LinReg, Trees
KNN is both Non-Parametric and Lazy. That combination makes it
simple, flexible, and interpretable — but slow at prediction and hungry
for clean, scaled features.
2.2 The Standard (Uniform) KNN Algorithm
Choose integer K = number of nearest neighbors.
Compute the distance between the query instance and every training example.
Sort distances (ascending) and keep the K smallest (the nearest K).
Gather the class labels of those K neighbors.
Return the simple majority class among the K neighbors as the prediction.
Classic k = 3 vs. k = 5 diagram
2.3 Distance Metrics
A valid metric d must satisfy four axioms: non-negativity d(x1,x2) ≥ 0; self-proximity d(x,x) = 0; symmetry d(x1,x2) = d(x2,x1); and triangle inequality d(x1,x2) ≤ d(x1,x3) + d(x3,x2).
Euclidean
Manhattan
Minkowski
L2 norm — straight-line distance between two points in ℝⁿ.
The salary difference of $50K completely dominates the 10-year age difference. After standardization, each feature is measured in SD units and both contribute fairly to the distance.
2.6 The Equal-Vote Problem and Weighted KNN
When "1-person-1-vote" goes wrong
K = 5 for a new query point. Neighbors of Class A sit at distances {0.1, 5.0}; neighbors of Class B sit at {4.8, 4.9, 5.1}. Standard KNN votes 3 B > 2 A → predicts B. But the single very close neighbor at distance 0.1 screams A!
The fix: distance-weighted voting. Give each neighbor a weight that decays with distance. Sum weights per class; pick the class with the largest sum.
Common weighting functions (weight w as a function of distance d)
Inverse distance: \( w_i = \dfrac{1}{d_i + \varepsilon} \) — simple, interpretable. The ε prevents division-by-zero on exactly-repeated training points.
1 − D: First normalize all K distances by the (K+1)th distance to get Dᵢ ∈ [0,1], then wᵢ = 1 − Dᵢ.
Convenience: sklearn.neighbors.KNeighborsClassifier has weights='distance' which uses inverse distance.
2.7 Weighted KNN Scoring Example from the Lecture
Scaled features, query point David needs a Yes/No prediction:
Neighbor
Scaled Distance
Class
Weight = 1/d
John
0.301
Yes
3.322
Rachael
0.316
No
3.165
Norah
0.631
Yes
1.585
Jefferson
0.832
No
1.202
Ruth
1.000
No
1.000
Standard KNN (counts): 3 No, 2 Yes → No
Weighted KNN (sum 1/d): Yes = 3.322+1.585 = 4.907; No = 3.165+1.202+1.000 = 5.367 → still No in this example, but the Yes class is much closer than simple counts suggest.
Why weighted is nice: It makes the exact value of k much less critical, because the natural fade of 1/d already down-weights the far neighbors regardless of whether k = 5 or 50.
2.8 Characteristics Summary of KNN
✅ Super simple — no complex math.
✅ No assumptions about data distribution — handles non-linear boundaries naturally.
✅ Inherently supports multi-class and incremental learning.
Prediction is O(n) per query (slow on big training sets — fix with KD/ball trees).
Extremely sensitive to irrelevant features and feature scale.
Breaks down in high dimensions (curse of dimensionality — Unit 6 topic).
3. Interactive Examples
Example 1: Classify a Point with k = 3 and k = 5
Given a tiny 2-D training set. Compute for yourself, then reveal.
Point
X
Y
Class
P1
0.3
0.7
A
P2
0.2
0.9
B
P3
0.6
0.6
A
P4
0.5
0.1
A
P5
0.7
0.7
B
P6
0.4
0.9
B
Query Q
0.2
0.6
?
Step 1: Compute Euclidean distances from Q to all 6 points (click)
(a) k = 3 neighbors: {A, B, B} → majority B → Predict Class B.
(b) k = 5 neighbors: {A, B, B, A, B} → 3 B, 2 A → Predict Class B.
Example 2: When Scaling Destroys the Distance
Scale-or-Not Scenario
Two features: house_sqft (range 800–4,000) and num_bedrooms (range 1–6).
House X: 1,200 sqft, 2 beds. House Y: 1,800 sqft, 3 beds.
Without any scaling, d(X,Y) ≈ √(600² + 1²) ≈ 600 — the bedroom difference is invisible.
What is the qualitative effect of applying Z-score standardization before distance?
If we used Manhattan distance instead of Euclidean on the raw values, would that help?
(a) Standardization rescales each feature to SD units. Typical SDs: sqft ≈ 700, bedrooms ≈ 1.2. SD units difference: sqft 600/700 ≈ 0.86 SD, bedrooms 1/1.2 ≈ 0.83 SD. After standardization, both features contribute approximately equally to the distance — exactly what we want.
(b) No. Manhattan on raw data still sums: 600 + 1 = 601. The bedroom difference still vanishes. All distance metrics need scale alignment when feature scales differ.
Example 3: Weighted KNN vs. Standard KNN
Click to see the scenario. Compute predictions for both variants.
Query point Q. K = 5. Distances and classes of nearest 5: { d=0.05 A, d=0.98 B, d=0.99 B, d=1.00 B, d=1.01 A }.
Prediction of standard KNN?
Prediction of weighted KNN using w = 1 / d?
Why is there a difference? Which is more sensible?
(a) Standard KNN counts: 3 B vs. 2 A → Predict B.
(b) Weights: A gets 1/0.05 + 1/1.01 ≈ 20 + 0.99 = 20.99. B gets 1/0.98 + 1/0.99 + 1/1.00 ≈ 1.02 + 1.01 + 1.00 = 3.03. Weighted sum A > B → Predict A.
(c) Difference arises because that one extremely close neighbor at d = 0.05 is a very strong signal for A. Weighted KNN is more sensible here because it respects proximity. Always compare weights='uniform' vs. weights='distance' in cross-validation.
4. Numerical Solutions
Problem 1: Manhattan, Euclidean, Chebyshev
Two 4-dimensional standardized points: p = [0.1, −0.3, 0.5, 0.0] and q = [0.3, 0.1, −0.2, 0.7]. Compute (a) Manhattan, (b) Euclidean, and (c) Chebyshev distance between them.
K = 4 (deliberately even, so ties can happen). Four nearest neighbors of a query: {d=0.2 → class 0, d=0.3 → class 1, d=0.5 → class 0, d=0.6 → class 1}.
Show that standard KNN gives a perfect 2/2 tie and describe two sensible tiebreakers.
Apply weighted KNN with w = 1 / d. Does this break the tie?
📘 Step-by-step solution
(a) Standard KNN counts: 2 votes for class 0, 2 votes for class 1 → tie 50/50. Common tiebreakers: (i) pick the class of the single nearest neighbor (class 0 wins); (ii) use weighted KNN; (iii) prefer the class with higher overall prior in the whole training set; (iv) randomly sample (weak!).
(b) Weights per neighbor: w(0@0.2) = 5; w(1@0.3) ≈ 3.333; w(0@0.5) = 2; w(1@0.6) ≈ 1.667. Sums: Class 0 total = 5 + 2 = 7; Class 1 total ≈ 3.333 + 1.667 = 5.00.
\( \text{Weighted class 0} = 7 > \text{Weighted class 1} = 5 \implies \text{Predict }\mathbf{0} \)
Yes — weighting cleanly resolves the tie in favor of the closer class-0 neighbors.
Problem 3: Sensitivity of k (Bias-Variance by Hand)
You have 8 training points, 2-D. Two are mislabeled noise: one red in a blue cluster, one blue in a red cluster. Answer qualitatively with justifications:
At k = 1, how do the two noisy points affect predictions in their immediate neighborhoods?
At k = 7, how do they affect predictions?
Which k value has higher variance? Higher bias?
📘 Step-by-step solution
(a) k = 1: The two mislabeled points each "own" a little Voronoi cell around themselves. Any query that lands nearer to them than to any correctly-labeled neighbor will be predicted wrong. That means the decision boundary ripples and changes drastically depending on exactly where the single noise points landed — classic high variance.
(b) k = 7 (out of 8): Every prediction is a near-majority vote over almost the whole dataset. The two noisy points contribute 2/7 of a vote to queries anywhere, shifting every prediction slightly but smoothly toward the wrong class. Decision boundary is very smooth but biased.
(c) k = 1 has higher variance (predictions depend on tiny local subsets; unstable across retraining). k = 7 has higher bias (underfitting — systematically ignoring the local structure). This is the bias-variance tradeoff in action.
5. Try It Yourself
Problem 1 — Minkowski Distance Practice
Two points on a 2-D standardized plane: a = (1.0, −0.5), b = (2.0, 1.5).
Compute Minkowski distance at order p = 1, p = 2, and p → ∞ (Chebyshev).
Verify numerically that d₁ ≥ d₂ ≥ d∞ on this example. Which metric most penalizes large individual coordinate errors?
(b) 3 ≥ 2.236 ≥ 2 ✓ holds. Lower-p metrics penalize large per-coordinate errors less than the sum; but wait — the reverse: higher-p → only the largest coordinate matters. So L∞ is actually the softest on small coordinate errors; L1 (Manhattan) accumulates everything. For penalizing a single bad coordinate, L∞ effectively ignores all the others — this is why L2 is the balanced default.
Problem 2 — Preprocessing Checklist for KNN
You are given an adult-income dataset with these features. For each column, say YES / NO / MAYBE for whether the described transformation should happen before KNN, with a one-sentence justification.
education_num (1 = Preschool through 16 = Doctorate) → Leave as is because it's already numeric?
native_country (42 countries) → One-hot encoding to 41 dummy columns?
Rows with missing occupation = ? → Drop rows?
YES. Continuous numeric feature; distance-based algorithm needs all features on SD scale.
NO. Never use LabelEncoder on nominal X features — it creates a fake ordering ("Private" < "Self-emp"?). One-hot encode instead.
MAYBE but still scale it. It is ordinal with known equal-ish steps, so leaving 1..16 is acceptable, but it should still be standardized along with the other numeric columns to avoid 16–1 range dominating SD-unit distances from age/income.
YES. Correct nominal encoding. (Bonus: 41 columns is high-dimensional for KNN, so consider pairing with chi-square feature selection later.)
MAYBE. If "?" is rare and not MCAR, impute or assign a dedicated Missing category + indicator rather than dropping the whole row.
Problem 3 — Weighted KNN with 1−D
We have K = 4 neighbors with distances to query: {1.0, 2.0, 3.0, 4.0}. The (K+1) = 5th neighbor's distance is 5.0 (used for normalization).
Compute normalized distances Dᵢ = dᵢ / dK+1 for i = 1..4.
Compute weights wᵢ = 1 − Dᵢ for each neighbor.
If neighbor classes are {C1, C2, C1, C2} respectively, which class wins the weighted vote?
Answer all 5 MCQs. Click on an option to get instant feedback.
Your score: 0 / 5
7. Key Takeaways
KNN is lazy + non-parametric. No training computation, no distributional assumptions, works on any shape of decision boundary — at the cost of slow O(n) predictions.
5-step algorithm: Choose K, compute all distances, sort, keep K nearest, return their majority class. That's the whole algorithm.
Distance metrics. Euclidean (L2) is the intuitive default; Manhattan (L1) is more outlier-robust; Minkowski generalizes both via order p.
K controls the bias-variance tradeoff. Small k → flexible, high variance, overfit risk. Large k → smooth, high bias, underfit risk. Tune via cross-validation; use odd k to avoid 2-class ties.
Scale before KNN, always. Standardization (Z-score) usually beats Min-Max here. Skip scaling → the highest-range feature essentially becomes the only feature.
Weighted KNN fixes the equal-vote problem. Use w = 1/d, or w = 1−D normalized, or Gaussian kernels. sklearn parameter: weights='distance'.
Weighting is a safety net. It reduces the sensitivity to the exact value of k because distant neighbors' contributions naturally fade. Always compare weighted vs. uniform during model selection.
8. Common Pitfalls
Forgetting to standardize features. Probably the #1 bug in beginner KNN code. A salary column in cents vs. age in years will make the distance function useless.
Choosing k using test-set performance. Test set should be used once, at the very end. Pick k via cross-validation on the training set — then evaluate final model once on the held-out test set.
Running brute-force KNN on 10⁶ training rows. Prediction is O(n) per query. For medium/large datasets use sklearn's algorithm='ball_tree' or 'kd_tree' to get sublinear queries.
Using weighted KNN without scaling. 1/d weighting compounds the scaling problem: an unscaled distance of 50,000 vs. 10 makes a mess of inverse distances, producing zero useful weights.
Setting k to n. Trivially predicts the majority class — good as a baseline only. Any real dataset has local structure that k = n simply ignores.
Applying KNN to extremely high-dim data without feature selection. The curse of dimensionality (Unit 6) makes all neighbors equally distant, so KNN degenerates into a coin flip.